package job

import (
	"gorm.io/gorm"
	"log"
	"short-link/internal/models"
	"short-link/pkg"
	"time"
)

func ClearExpiresURLs(db *gorm.DB) {
	ticker := time.NewTicker(pkg.Config.Server.ClearUpInterval)
	defer ticker.Stop()

	for range ticker.C {
		log.Println("Starting cleanup of expired URLs...")
		now := time.Now()

		// Delete expired URLs
		res := db.Delete(&models.Url{}, "expires_at < ?", now)
		if res.Error != nil {
			log.Printf("delete expired urls error: %s\n", res.Error)
			return
		}
		log.Printf("Cleanup of expired URLs completed. %d has been cleared", res.RowsAffected)
	}
}
